package logic

import (
	"context"
	"errors"
	"video-manager/model/cache"
	"video-manager/model/mysql"
	"video-manager/pkg"

	"video-manager/usersrpc/internal/svc"
	"video-manager/usersrpc/usersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ResetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetPasswordLogic {
	return &ResetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ResetPasswordLogic) ResetPassword(in *usersrpc.ResetPasswordRequest) (*usersrpc.ResetPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User

	if err := findUser.FindUserByPhoneNum(mysql.DB, in.PhoneNum); err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("账号不存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "smsCode"+in.PhoneNum).Result()
	if result != in.SmsCode {
		return nil, errors.New("验证码错误，请重新登录")
	}
	if in.PassWord != in.NwePassWord {
		return nil, errors.New("两次输入密码不一致")
	}
	findUser.Pwd = pkg.MD5(in.NwePassWord)

	if err := findUser.ResetPassword(mysql.DB); err != nil {
		return nil, errors.New("修改错误")
	}
	return &usersrpc.ResetPasswordResponse{
		UserId: int64(findUser.ID),
	}, nil
}
